<template>
	<view class="main">
		<!-- 头部信息 -->
		<view class="msg_time" v-if="isTimeshow(msg.timestamp, lastTimestamp)">
			<view class="">
				<text>{{ formatMessageTime(msg.timestamp) }}</text>
			</view>
			<view class="">
				<text>{{ formatDistance(msg) }}</text>
			</view>
		</view>
		<view class="item" :id="`msga-${msg.timestamp}`" :class="msg.userTel === storeData.user.userTel ? 'push' : 'pull'">
			<view class="" @click="toUser">
					<image v-if="msg.nicPic.url" :src="msg.nicPic.url" mode="aspectFill" class="pic" ></image>
			<avatar-fallback v-else :name="msg.nicName"></avatar-fallback>
			</view>
		
			<view class="" style="display: flex; flex-direction: column">
				<view class="userId" v-if="msg.userTel !== storeData.user.userTel">
					{{ msg.nicName ? msg.nicName : msg.sendUserId }}
				</view>

				<view :class="msg.sendUserId === storeData.user.userId ? 'push-content' : 'pull-content'">
					<view class="message-content">
						<slot></slot>
					</view>
					<view class="content_foot">
						<view class="message-actions">
							<view class="action-btn" @click="handleReMsg(msg)" v-if="isReMsg">
								<uni-icons type="chat" size="20" color="#55aaff" class="iconfont icon-reply"></uni-icons>
								<text style="font-size: 26rpx; color: #afafaf">{{ resMsgList.length }}</text>
							</view>

							<view class="action-btn" @click="handleCollec" v-if="isCollect">
								<uni-icons class="iconfont" size="20" color="red" :type="isCollected() ? 'heart-filled' : 'heart'"></uni-icons>
								<text style="font-size: 26rpx; color: #afafaf">{{ msg.collect ? msg.collect.length : 0 }}</text>
							</view>
						</view>
					</view>
					<view class="filter" @click="filter(msg)">
						<uni-icons class="more-filled" size="20" color="#cacaca" type="more-filled"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 提示信息弹窗 -->
		<uni-popup ref="popup" class="popup" borderRadius="10px 10px 10px 10px" background-color="#fff" type="center">
			<view class="popup_title">信息选择功能</view>
			<view class="popup_list" v-for="(item, index) in popupList" :key="index">
				<view class="popup_list_item">
					<text class="popup_list_text">{{ item.text }}</text>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="remsg" class="uni-popup-top">
			<uni-popup-dialog mode="input" type="info" placeholder="请输入回复内容" :value="resMsg" :title="reMsgTitle" @confirm="confirmReMsg"></uni-popup-dialog>
		</uni-popup>

		<myReMsg :reMsgs="resMsgList" :msg="msg" v-if="showReMsg" @close="showReMsg = false"></myReMsg>
	</view>
</template>

<script>
import formatMessageTime from '@/utils/formatMessageTime.js';
import { formatDistance } from '@/utils/distance.js';
const linliChat = uniCloud.importObject('linliChat', { customUI: true });
import setToTarget from '../utils/setTarget';
import myReMsg from './myReMsg.vue';
import AvatarFallback from './AvatarFallback.vue';
export default {
	props: {
		// 发送者名称

		msg: {
			type: Object,
			required: true
		},
		lastTimestamp: {
			type: Number,
			default: 0
		},
		isCollect: {
			type: Boolean,
			default: true
		},
		isReMsg: {
			type: Boolean,
			default: true
		}
	},
	components: {
		myReMsg,
		AvatarFallback
	},
	data() {
		return {
			popupList: [
				{ text: '屏蔽此人', value: 1 },
				{ text: '屏蔽此类型', value: 2 },
				{ text: '举报该信息', value: 3 }
			],

			resMsg: '',
			showReMsg: false,
			resMsgList: [],
			reMsgTitle: '',
			msgTypeMap: {
				1: '语音信息',
				2: '文字聊天',
				3: '图片信息',
				4: '商品售卖',
				5: '店铺信息',
				6: '视频内容'
			}
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		}
	},
	mounted() {
		this.getCommentMsg();
	},

	methods: {
		mainPageClickEven() {
			uni.$emit('mainPageClickEven');
		},
		formatMessageTime,
		formatDistance(item) {
			return formatDistance(this.storeData.senderLocation, item);
		},
		filter(msg) {
			this.popupList = [{ text: `屏蔽信息发送人:${msg.nicName}` }, { text: `屏蔽所有"${this.msgTypeMap[msg.messageType]}类型"信息` }, { text: '举报此信息' }];

			this.$refs.popup.open();
		},
		isTimeshow(timestamp, lastTimestamp) {
			if (lastTimestamp > 0) {
				if (timestamp - lastTimestamp < 300000) {
					return false;
				} else if (!timestamp) {
					return false;
				} else {
					return true;
				}
			}
		},
		async handleCollec() {
			// 检查必要数据是否存在
			console.log('收藏操作开始');
			if (!this.msg) {
				uni.showToast({
					title: '消息数据不存在',
					icon: 'none'
				});
				return;
			}

			// 初始化收藏数组（避免undefined）
			const collectList = this.msg.collect || [];
			const userId = this.storeData?.user?.userId;

			// 检查用户ID是否存在
			if (!userId) {
				uni.showToast({
					title: '未获取到用户信息',
					icon: 'none'
				});
				return;
			}

			try {
				// 判断当前用户是否已收藏（修复箭头函数语法）
				const isCollected = collectList.some((item) => item === userId);
				const type = isCollected ? 'del' : 'add';

				// 调用收藏接口
				console.log(userId, this.msg._id, type);
				const result = await linliChat.collect({
					publicMsgId: this.msg._id,
					sendUserId: userId,
					type: type
				});
				console.log(',,,,', result);
				uni.showToast({
					icon: 'none',
					title: result.msg || (result.code ? '操作成功' : '操作失败'),
					duration: 2000
				});
				var collect = [];
				// 操作成功后更新本地收藏状态（避免重新请求接口）
				if (result.code) {
					if (type === 'add') {
						collect = [...collectList, userId];
					} else {
						collect = collectList.filter((item) => item !== userId);
					}
					const newmsg = { ...this.msg, collect: collect };
					uni.$emit('msgUpdata', newmsg);
				}
			} catch (error) {
				console.error('收藏操作失败', error);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			}
		},
		isCollected() {
			const collectList = this.msg.collect || [];

			return collectList.some((item) => item === this.storeData.user.userId);
		},

		toUser() {
			if (this.msg.sendUserId !== this.storeData.user.userId) {
				const queryParam = {};
				queryParam.id = this.msg.sendUserId;
				queryParam.type = 'person';
				this.$store.commit('msg/SET_queryParam', queryParam);
				setToTarget('person', { targetId: this.msg.sendUserId, nicName: this.msg.nicName, nicPic: this.msg.nicPic.url });

				uni.navigateTo({
					url: '/pages/messages/messages'
				});
			} else {
				uni.navigateTo({
					url: '/pages/me/me'
				});
			}
		},

		handleSelect(e) {
			console.log(e);
		},
		async getCommentMsg() {
			const res = await linliChat.commentMsg({ type: 'get', publicMsgId: this.msg._id });
			if (res.code) {
				this.resMsgList = res.data;
			}
		},
		handleReMsg(msg) {
			if (msg.sendUserId === this.storeData.user.userId) {
				this.showReMsg = true;
			} else {
				this.reMsgTitle = `对${msg.nicName}信息发表评论`;
				this.$refs.remsg.open();
			}
		},
		async confirmReMsg(val) {
			if (!val || val.trim() === '') {
				uni.showToast({
					title: '请输入评论内容',
					icon: 'none'
				});
				return;
			}

			try {
				// 调用评论接口，传递完整参数

				const result = await linliChat.commentMsg({
					type: 'add', // 指定操作类型为新增评论
					sendUserId: this.storeData.user.userId, // 当前登录用户ID
					content: val.trim(), // 评论内容
					publicMsgId: this.msg._id // 被评论的消息ID
				});
				console.log(result);
				if (result.code) {
					uni.showToast({
						title: '回复成功',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: result.msg || '评论失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('评论接口调用失败', error);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			}
		}
	}
};
</script>

<style scoped>
.popup_list {
	padding: 20rpx 50rpx;
}
.popup_title {
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
	flex: 1;
	padding: 10rpx;
	background-color: #bfbfbf;
}
.popup_list_text {
	font-size: 30rpx;
}
/* 头部信息样式 */
.message-header {
	margin-bottom: 20rpx;
}

.sender-info {
	display: flex;
	flex-direction: row;
	align-items: center;
}

.sender-details {
	display: flex;
	flex-direction: row;
	padding: 0 10rpx;
	flex: 1;
}
.filter {
	position: absolute;
	top: 8rpx;
	right: 10rpx;
}

.sender-name {
	display: flex;
	color: #a6a6a6;
	font-size: 22rpx;
	padding-bottom: 5rpx;
	margin-bottom: 5rpx;
	display: flex;
	margin-left: 20rpx;
	flex-direction: row;
}

.sender-meta {
	display: flex;
	flex-direction: row;
	align-items: center;
	color: #838383;
	font-size: 24rpx;
}

.content_foot {
	display: flex;
	flex-direction: row;
	justify-content: space-around;
}
/* 操作按钮样式 */
.message-actions {
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	width: 200rpx;
	height: 40rpx;
	padding-left: 20rpx;
}

.action-btn {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: center;
	margin-left: 10rpx;
}

.reply-btn {
	background-color: #f0f7ff;
	color: #007aff;
}
.btn-text {
	font-size: 26rpx;
}
.collect-btn {
	background-color: #fff8f0;
	color: #ff9500;
}
.main {
	width: 100%;
}
.userpic {
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	width: 60rpx;
	border-radius: 50%;
	margin-right: 32rpx;
}
.userId {
	display: flex;
	color: #a6a6a6;
	font-size: 22rpx;
	padding-left: 30rpx;
	padding-bottom: 5rpx;
}
.nicimg {
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
}
.msg_time {
	display: flex;
	width: 100%;
	/* 1. 文本水平居中（margin:0 auto 是容器居中，text-align 是文本在容器内居中） */
	text-align: center;
	/* 2. 容器水平居中（配合 width:100% 确保占满父容器，margin 生效） */
	align-items: center;
	justify-content: center;
	margin-top: 15rpx;
	color: #969696;
	font-size: 24rpx;
	/* 3. 可选：限制时间戳背景，增强视觉区分 */
	padding: 5rpx 0;
	gap: 20rpx;
}
.item {
	padding: 15rpx 20rpx 15rpx 20rpx; // 上下各 15rpx 间距，左右保持 20rpx
	margin-bottom: 5rpx; // 可选：额外增加底部外边距，强化分隔
	align-items: flex-start;
	align-content: flex-start;
	color: #333;
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	justify-content: flex-start;
}

/* 收到的消息 */
.pull {
}

.pull-content {
	margin-left: 32rpx;
	background-color: #fff;
	padding: 15rpx;
	border-radius: 4px;
	max-width: 500rpx;
	word-break: break-all;
	position: relative;
	&::after {
		content: '';
		display: flex;
		width: 0;
		height: 0;
		border-top: 16rpx solid transparent;
		border-bottom: 16rpx solid transparent;
		border-right: 20rpx solid #fff;
		position: absolute;
		top: 30rpx;
		left: -18rpx;
	}
}
/* 发出的消息 */
.push {
	/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
	flex-direction: row-reverse;
}
.push-content {
	flex-direction: row-reverse;
	margin-right: 32rpx;
	background-color: #ffffff;
	padding: 15rpx;
	border-radius: 4px;
	max-width: 500rpx;
	word-break: break-all;
	line-height: 45rpx;
	position: relative;
	&::after {
		content: '';
		display: flex;
		width: 0;
		height: 0;
		border-top: 16rpx solid transparent;
		border-bottom: 16rpx solid transparent;
		border-left: 20rpx solid #ffffff;
		position: absolute;
		top: 30rpx;
		right: -18rpx;
	}
}
.pic {
	width: 60rpx;
	height: 60rpx;
	border-radius: 15%;
	border: #e1e1e1 solid 1px;
}
.content {
	padding: 15rpx;
	border-radius: 4px;
	max-width: 500rpx;
	word-break: break-all;
	line-height: 45rpx;
	position: relative;
}
</style>
